package com.xxgc.cloud.springcloudgateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTUtil;
import com.xxgc.cloud.api.jwt.IUserAuthInfo;
import com.xxgc.cloud.common.redis.RedisClient;
import com.xxgc.cloud.springcloudgateway.config.SwaggerProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.cloud.gateway.support.GatewayToStringStyler;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @program: SpringCloudStudy
 * @description: Token过滤工厂
 * @author: Mr.abel(ShiJiaYi)
 * @create: 2022-11-29 16:55
 **/
@Component
@Slf4j
public class TokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Autowired
    private JwtConfig jc;

    @Autowired
    private RedisClient redisClient;

    @DubboReference(
            interfaceClass = IUserAuthInfo.class,
            version = "1.0.0",
            check = false)
    private IUserAuthInfo iuai;

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter(){
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //获取请求对象
                ServerHttpRequest request = exchange.getRequest();
                //获取响应对象
                ServerHttpResponse response = exchange.getResponse();
                //放开swagger
                String s = request.getPath().toString();
                if(s.equals(SwaggerProvider.SWAGGER2URL)){
                    return chain.filter(exchange);//放行
                }
                //获取头部
                HttpHeaders headers = request.getHeaders();
                //从请求头部获取token
                String token = headers.getFirst(HttpHeaders.AUTHORIZATION);
                //如果token为空
                if(StrUtil.hasBlank(token)){
                    //设置一个未授权的状态
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
                //进行token验证
                boolean verify;
                try {
                    verify = JWTUtil.verify(token, jc.getJwtKey().getBytes());
                }catch (JWTException e){ //对非法的token进行捕获
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
                if(!verify){
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
                //token过期判断
                final JWT jwt = JWTUtil.parseToken(token).setKey(jc.getJwtKey().getBytes());
                boolean verifyTime = jwt.validate(0);
                if(!verifyTime){
                    response.setStatusCode(HttpStatus.FORBIDDEN);
                    return response.setComplete();
                }
                //判断用户是否被锁定
                Integer uid = (Integer) jwt.getPayload("uid");
                Boolean userLocking = iuai.selectUserLockingById(uid);
                if(userLocking){
                    response.setStatusCode(HttpStatus.LOCKED);
                    return response.setComplete();
                }
                //redis是否还有这个key 强制下线
                String reidsKey = jc.getRedisLoginKey() + uid;
                Boolean exists = redisClient.exists(reidsKey);
                if(!exists){
                    response.setStatusCode(HttpStatus.FORBIDDEN);
                    return response.setComplete();
                }

                return chain.filter(exchange);//放行
            }

            @Override
            public String toString() {
                return GatewayToStringStyler.filterToStringCreator(TokenGatewayFilterFactory.this).append(config.getName(), config.getValue()).toString();
            }
        };
    }
}
